<template>
  <div class="grading-management">
    <!-- 搜索区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="作业ID">
            <el-input v-model="filterForm.assignmentId" placeholder="请输入作业ID" @keyup.enter="queryAllHomeworkList"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="学生姓名">
            <el-input v-model="filterForm.studentName" placeholder="请输入学生姓名" @keyup.enter="queryAllHomeworkList"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item>
            <el-button type="primary" @click="queryAllHomeworkList">查询</el-button>
            <el-button type="default" @click="resetFilter">重置</el-button>
            <el-button type="success" @click="confirmGradingComplete">确认批改完成</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="作业统计">
            <div class="stats-container">
              <span class="stat-item">未提交: {{ stats.unsubmittedCount }}</span>
              <span class="stat-item">未批改: {{ stats.ungradedCount }}</span>
              <span class="stat-item">已提交: {{ stats.submittedCount }}</span>
            </div>
          </el-form-item>
        </el-col>

      </el-row>
    </el-card>

    <!-- 作业列表 -->
    <el-card class="homework-list-card">
      <div class="table-container">
        <el-table :data="homeworkList" stripe border @row-dblclick="handleRowClick" style="width: 100%;" max-height="500px">
          <el-table-column prop="assignmentId" label="作业ID"></el-table-column>
          <el-table-column prop="submissionId" label="作业提交ID"></el-table-column>
          <el-table-column prop="title" label="作业标题"></el-table-column>
          <el-table-column prop="content" label="作业内容"></el-table-column>
          <el-table-column prop="studentName" label="学生姓名"></el-table-column>
          <el-table-column prop="className" label="班级"></el-table-column>
          <el-table-column prop="subDate" label="提交时间"></el-table-column>
          <el-table-column prop="state" label="作业状态">
            <template #default="scope">
              {{ scope.row.state === '1' ? '未提交' : scope.row.state === '2' ? '未批改' : scope.row.state === '3' ? '已批改' : '未知' }}
            </template>
          </el-table-column>
          <el-table-column prop="feedback" label="反馈"></el-table-column>
          <el-table-column prop="grade" label="成绩"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button v-if="scope.row.state === '2'" type="primary" size="small" @click="handleGrade(scope.row)">批改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 批改作业对话框 -->
    <el-dialog v-model="gradeDialogVisible" title="批改作业" width="50%" @close="handleGradeDialogClose">
      <el-form :model="gradeForm" ref="gradeFormRef" label-width="120px" :rules="gradeFormRules">
        <el-form-item label="作业ID" prop="assignmentId">
          <el-input v-model="gradeForm.assignmentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="gradeForm.studentName" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业标题" prop="title">
          <el-input v-model="gradeForm.title" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业内容" prop="content">
          <el-input v-model="gradeForm.content" disabled></el-input>
        </el-form-item>
        <el-form-item label="成绩" prop="grade">
          <el-input v-model="gradeForm.grade"></el-input>
        </el-form-item>
        <el-form-item label="评语" prop="comment">
          <el-input v-model="gradeForm.comment" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="批改附件" prop="file">
          <el-upload
              ref="uploadRef"
              action="#"
              :show-file-list="false"
              :on-change="handleFileChange"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="gradeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGradeForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from 'vue-router';
const route = useRoute();

// 筛选条件
const filterForm = reactive({
  assignmentId: "" || route.query.assignmentId,
  classIds: "" || route.query.classIds
});

// 表格数据和分页
const homeworkList = ref([]);
const allHomeworkList = ref([]); // 存储所有页的数据
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 批改作业对话框相关
const gradeDialogVisible = ref(false);
const gradeForm = ref({
  assignmentId: "",
  studentId: "",
  studentName: "",
  title: "",
  content: "",
  grade: "",
  comment: "",
  file: null,
});
const gradeFormRef = ref(null);
const uploadRef = ref(null);

const confirmGradingComplete = async () => {
  const { unsubmittedCount, ungradedCount } = stats.value;

  // 存在未批改作业，阻止操作
  if (ungradedCount > 0) {
    ElMessageBox.alert('存在未批改的作业，请完成所有批改后再确认！', '提示', {
      confirmButtonText: '确定',
      type: 'warning',
    });
    return;
  }

  // 仅存在未提交作业，询问是否继续
  if (unsubmittedCount > 0) {
    try {
      await ElMessageBox.confirm(
          `存在${unsubmittedCount}份未提交作业，是否继续确认批改完成？`,
          '提示',
          {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning',
          }
      );
      // 用户点击继续，执行确认操作
    } catch (error) {
      // 用户点击取消，取消操作
      return;
    }
  }

  // 执行确认批改完成逻辑
  try {
    const formData = new FormData();
    formData.append("assignmentId", route.query.assignmentId);
    formData.append("state", 2);
    const res = await axios.post('/assignments/updateAssignment', formData);
    if (res.data.result) {
      ElMessage.success("作业任务已标记为已批改！");
    } else {
      ElMessage.error("标记失败，请稍后重试！");
    }
  } catch (err) {
    console.error("标记作业任务为已批改失败", err);
    ElMessage.error("标记失败，请稍后重试！");
  }
};

// 查询所有页的作业列表
const queryAllHomeworkList = async () => {
  try {
    // 先获取总页数
    const formData = new FormData();
    formData.append("classIds", filterForm.classIds);
    formData.append("assignmentId", Number(filterForm.assignmentId));
    formData.append("page", 1);
    formData.append("size", pageSize.value);
    const firstPageResponse = await axios.post("/submissions/getSubmissionList", formData);
    total.value = firstPageResponse.data.total || 0;
    const totalPages = Math.ceil(total.value / pageSize.value);

    allHomeworkList.value = [];
    for (let page = 1; page <= totalPages; page++) {
      formData.set("page", page);
      const response = await axios.post("/submissions/getSubmissionList", formData);
      allHomeworkList.value = allHomeworkList.value.concat(response.data.result || []);
    }

    homeworkList.value = allHomeworkList.value.slice(0, pageSize.value);
  } catch (error) {
    console.error("获取作业列表失败", error);
    ElMessage.error("获取作业列表失败，请稍后重试");
  }
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.assignmentId = "";
  filterForm.studentName = "";
  queryAllHomeworkList();
};

// 分页控制
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  queryAllHomeworkList();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  const startIndex = (newPage - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  homeworkList.value = allHomeworkList.value.slice(startIndex, endIndex);
};

// 处理批改作业
const handleGrade = (row) => {
  gradeDialogVisible.value = true;
  gradeForm.value = {
    assignmentId: row.assignmentId,
    studentId: row.studentId,
    studentName: row.studentName,
    title: row.title,
    content: row.content,
    grade: "",
    comment: "",
    file: null,
  };
};

// 提交批改信息
const submitGradeForm = async () => {
  await gradeFormRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    try {
      const formData = new FormData();
      const { assignmentId, studentId, grade, comment, file } = gradeForm.value;
      formData.append("assignmentId", assignmentId);
      formData.append("studentId", studentId);
      formData.append("grade", grade);
      formData.append("feedback", comment);
      if (file) {
        formData.append("file", file);
      }

      const response = await axios.post("/submissions/updateSubmissionTea", formData);
      if (response.data.flag) {
        ElMessage.success("作业批改成功！");
        gradeDialogVisible.value = false;
        gradeFormRef.value.resetFields();
        uploadRef.value.clearFiles();
        queryAllHomeworkList();
      } else {
        ElMessage.error("批改失败！");
      }
    } catch (error) {
      console.log(error);
    }
  });
};

// 批改表单验证规则
const gradeFormRules = computed(() => ({
  grade: [
    { required: true, message: "请输入成绩", trigger: "blur" },
  ],
  comment: [
    { required: true, message: "请输入评语", trigger: "blur" },
  ],
}));

// 处理批改对话框关闭
const handleGradeDialogClose = () => {
  gradeDialogVisible.value = false;
  gradeForm.value = {};
  uploadRef.value.clearFiles();
};

// 处理文件选择
const handleFileChange = (file) => {
  gradeForm.value.file = file.raw;
};

// 新增计算属性，用于统计不同状态的作业人数
const stats = computed(() => {
  let unsubmittedCount = 0;
  let ungradedCount = 0;
  let submittedCount = 0;

  allHomeworkList.value.forEach(item => {
    if (item.state === '1') {
      unsubmittedCount++;
    } else if (item.state === '2') {
      ungradedCount++;
      submittedCount++;
    } else if (item.state === '3') {
      submittedCount++;
    }
  });

  return {
    unsubmittedCount,
    ungradedCount,
    submittedCount
  };
});

onMounted(() => {
  queryAllHomeworkList();
});
</script>

<style scoped>
.grading-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.homework-list-card {
  height: auto;
  margin-bottom: 20px;
}

.table-container {
  height: 500px;
  overflow-y: auto;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.stats-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.stat-item {
  white-space: nowrap;
}
</style>